-- lua wireshark plugin
-- Wireshark Version 2.4.2
-- 主调用脚本
-- 2024-08-22




--[[ 
填写端口对应的脚本文件
格式：["文件名"] = {源端口号1, 源端口号2}
]]--

local script_table = {

["template.lua"] = {52103, 52014},
["template1.lua"] = {28310, 40001}


}






--[[------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


																					此处以下内容禁止修改


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]--



function write_log_to_file(text)
	local file = io.open("log.txt", "a")
	file:write(tostring(text).."\n")
	file:close()
end


function split(input, delimiter)
    local result = {}
    for match in (input..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end


local package = require("package")
package.loaded["debug"] = package.preload["debug"] or package.loaded["debug"] or function() end
local debug = require("debug")

-- 获取Wireshark安装目录的路径
local wireshark_install_dir = Dir.global_config_path()  -- 获取Wireshark的全局配置目录
wireshark_install_dir = wireshark_install_dir:gsub("plugins.*$", "")  -- 删除plugins目录及其后面的部分

-- 获取当前脚本的绝对路径
local function get_script_path()
    local info = debug.getinfo(1, "S")
    return info.source:sub(2)  -- 去掉路径前面的 "@"
end

-- 计算相对路径
local function get_relative_script_path()
    local script_path = get_script_path()
    local relative_path = script_path:sub(#wireshark_install_dir + 1)
    return relative_path
end

local relative_script_path = get_relative_script_path()

local str_list = split(relative_script_path, "\\")


-- 主协议，全局变量
protocol = Proto("FITSCO_Proto", "General Protocol")

local sub_proto_tables = {}


for key, port_tb in pairs(script_table) do
	local sub_tb = dofile(str_list[1].. "\\".. key)
	for _,port in pairs(port_tb) do
		sub_proto_tables[port] = sub_tb
	end
end



function protocol.dissector(tvb, pinfo, tree)

	local udp_port = pinfo.src_port
	local sub_tb = sub_proto_tables[udp_port]

	local sub_dissector = sub_tb[1]
	
	sub_dissector.dissector(tvb, pinfo, tree)
	
end

local udp_dissector_table = DissectorTable.get("udp.port")



for key, port_tb in pairs(script_table) do
	for _,port in pairs(port_tb) do

		DissectorTable.get("udp.port"):add(port, protocol)
	end
end



